#!/usr/bin/perl

# package de parsing dess document Rubis
package LPD::Parser;
use Carp;
use Data::Dumper;
use POSIX qw(strftime);
use JSON;

sub new {
	my($class)  = shift;
	my(%params) = @_;
	my $self  = {
		'_header' => {},
		'_document' => [],
		'_buffer' => ''
	};
	bless ($self, $class);
	return $self;
}

########################### PUBLIC ###############################################
sub parse {
	my $self = shift;
	$self->{'_buffer'} = shift;

	my @buffer = split("\n",$self->{'_buffer'});

	my %header;
	my @document ;
	my $flag_document	= 0;
	my $flag_header		= 0;
	for(my $i=0 ; $i<$#buffer ; $i++) {
		my $ligne = $buffer[$i];
		if		($i == 0 && $ligne =~ /^\x0C(.*)/) { # premiere ligne
			$self->{'_header'}->{'queue'} = $1;
		} elsif ($i == 1 && $ligne =~ /^\x03(\d+)/) { # deuxieme ligne
			$self->{'_header'}->{'jobid'} = $1;
		} elsif ($ligne =~ /^\x00\.(.*)/ && !$flag_document) { #premiere ligne de texte
			push @{$self->{'_document'}}, $1;
			$flag_document = 1;
		} elsif ($ligne =~ /^\x0D\x0C\x00\x02/) { # on arrive dans le header
			$flag_document	= 0;
			$flag_header	= 1;
		} else {
			if		($flag_document) { #on stock les lignes du document
				push @{$self->{'_document'}}, $ligne;
			} elsif ($flag_header) { #on stock les lignes du header
				if		($ligne =~ /^H(.*)/) { $self->{'_header'}->{'host'} = $1; }
				elsif	($ligne =~ /^P(.*)/) { $self->{'_header'}->{'user'} = $1; }
				elsif	($ligne =~ /^J(.*)/) { $self->{'_header'}->{'jobname'} = $1; }
			}
		}
	}

	$self->{'_header'}->{'datetime'} = strftime('%Y-%m-%d %H:%M:%S', localtime);
}


sub getXML {
	my $self = shift;
	my $return = '';
	
	# generating XML output file
	$return .= '<?xml version="1.0" encoding="iso-8859-1"?>'."\n";
	$return .= "<document\n";
	foreach my $k (keys %{$self->{'_header'}}) { $return .= "\t$k=\"".$self->{'_header'}->{$k}."\"\n"; }
	$return .= "><![CDATA[\n";
	foreach my $v (@{$self->{'_document'}}) { $return .= "$v\n"; }
	$return .= "]]>\n</document>\n";

	return $return;
}


sub getJSON {
	my $self = shift;
	my $return = '';
	
	my $json = {	'header'=>$self->{'_header'},
					'document'=>join("\n",@{$self->{'_document'}})
				};

	$return = encode_json $json;

	return $return;
}

1;